package com.hefei.blog.base.upload.image;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import com.hefei.blog.base.exception.MtonsException;
import com.hefei.blog.base.upload.consts.FileConsts;
import com.hefei.blog.base.utils.FileNameUtils;
import com.hefei.blog.base.utils.FilePathUtils;

public class UploadImageUtils {

	/**
	 * @param file
	 * @param basePath
	 * @return 相对路径 /ava/2017/11/12/12345abcd.jpg /pic/2017/11/12/12345abcd.jpg
	 * @throws IOException
	 */
	public static String upload(MultipartFile file, String basePath) throws IOException {
		validateFile(file);
		
		String root = FileConsts.ROOT_PIC;
		
		String extWithoutDot = FileNameUtils.getExt(file.getOriginalFilename(), false);//jpg\bmp
		String name = FileNameUtils.randomFileName(extWithoutDot);//120012xjik.jpg
		String path = basePath + name;
		File temp = new File(root + path);
		FilePathUtils.checkDirAndCreate(temp);
		file.transferTo(temp);
		return path;
	}
	/**
	 * @param file
	 * @param basePath /ava/2017/11/12/
	 * @return 相对路径 /ava/2017/11/12/12345abcd.jpg /pic/2017/11/12/12345abcd.jpg
	 * @throws IOException
	 */
	public static String upload(File file, String basePath) throws IOException {
		validateFile(file);
		
		String root = FileConsts.ROOT_PIC;
		String extWithoutDot = FileNameUtils.getExt(file.getCanonicalPath(), false);//jpg\bmp
		String name = FileNameUtils.randomFileName(extWithoutDot);//120012xjik.jpg
		String path = basePath + name;
		
		File dest = new File(root + path);
		FilePathUtils.checkDirAndCreate(dest);
		FileUtils.copyDirectory(file, dest);
		return path;
	}
	
	private static void validateFile(MultipartFile file) {
		if (file == null || file.isEmpty()) {
			throw new MtonsException("文件不能为空");
		}
		if (!FileNameUtils.checkImageFileType(file.getOriginalFilename())) {
			throw new MtonsException("文件格式不支持");
    	}
	}
	
	private static void validateFile(File file) {
		if (file == null) {
			throw new MtonsException("文件不能为空");
		}
		if (!FileNameUtils.checkImageFileType(file.getName())) {
			throw new MtonsException("文件格式不支持");
    	}
	}
}
